package covertjava.profile;

/**
 * <p>Demonstrates a thread deadlock</p>
 * <p>Copyright: Copyright (c) 2004 Sams Publishing</p>
 * @author Alex Kalinovsky
 * @version 1.0
 */
public class ThreadTest {

    public static Object lock1 = new Object();
    public static Object lock2 = new Object();

    public static void method1() {
        trace("Inside method1");
        synchronized (lock1) {
            trace("Method1 got lock1");
            doSomething();
            synchronized (lock2) {
                trace("Method1 got lock2, sleeping");
                doSomething();
                trace("Method1 returning");
            }
        }
    }


    public static void method2() {
        trace("Inside method2");
        synchronized (lock2) {
            trace("Method2 got lock2");
            doSomething();
            synchronized (lock1) {
                trace("Method2 got lock1, sleeping");
                doSomething();
                trace("Method2 returning");
            }
        }
    }


    public static void doSomething() {
        try {
            Thread.sleep(5*1000);
        }
        catch (InterruptedException x) {
            x.printStackTrace();
        }
        trace("Waiking up");
    }


    public static void trace(String msg) {
        System.out.println(Thread.currentThread() + " : " + msg);
    }


    public static void main(String[] args) throws Exception {
        new Thread(new Runnable() {
            public void run() {
                method1();
            }
        }).start();
        new Thread(new Runnable() {
            public void run() {
                method2();
            }
        }).start();
    }
}
